<template>
  <page-header-wrapper>
    <page-tab-list></page-tab-list>

    <a-card :border="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.is_enable" @change="getList()">
          <a-radio-button v-for="item of statusList" :key="item.id" :value="item.id"> {{ item.name }} </a-radio-button>
        </a-radio-group>

        <div style="display: flex">
          <a-button type="primary" style="margin-right: 10px" @click="visible = true">+ 新增</a-button>
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="handleAll('remove', '2')">批量删除</a-menu-item>
              <a-menu-item @click="handleAll('change', '1')" v-if="queryParam.status != '1'">批量开启</a-menu-item>
              <a-menu-item @click="handleAll('change', '0')" v-if="queryParam.status != '0'">批量关闭</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown>
        </div>
      </div>

      <a-table
        :row-key="(record) => record.id"
        :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
        :pagination="{
          total: this.totalCount,
          showSizeChanger: true,
          onChange: this.getList,
          onShowSizeChange: this.paginationSizeChange,
        }"
        :data-source="list"
        :loading="loading"
        :columns="columns"
      >
        <span slot="switch" slot-scope="text, record">
          <a-switch
            :checked="record.is_enable === '1' ? true : false"
            checked-children="开"
            un-checked-children="关"
            @change="handleItem('change', record)"
          />
        </span>

        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleItem('edit', record)" size="small">编辑</a-button>
          <a-divider type="vertical" />
          <a-button type="link" @click="handleItem('remove', record)" size="small">删除</a-button>
        </span>
      </a-table>

      <a-modal :title="getTitle" :visible="visible" @ok="onSubmit" width="800px" @cancel="visible = false">
        <a-form-model
          :loading="loading"
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-model-item label="规则名称" prop="name">
            <a-input v-model="form.name"></a-input>
          </a-form-model-item>

          <a-form-model-item label="是否启用" prop="is_enable">
            <a-radio-group v-model="form.is_enable">
              <a-radio :value="1"> 开启 </a-radio>
              <a-radio :value="0"> 关闭 </a-radio>
            </a-radio-group>
          </a-form-model-item>

          <a-form-model-item label="选择区域">
            <a-card
              v-for="(province, index) in province_list"
              size="small"
              :key="index"
              style="margin-bottom: 10px; max-height: 500px; overflow-y: scroll"
            >
              <a-button slot="extra" size="small" @click="province_list.splice(index, 1)">删除</a-button>
              <a-row type="flex">
                <span
                  style="margin-right: 10px"
                  v-for="(item, index1) of province.province_list"
                  :key="index + '' + index1"
                >
                  {{ item.name }}
                </span>
              </a-row>
            </a-card>
            <a-button @click="showInfoStatus = true" icon="plus" size="small"> 新增条目 </a-button>
          </a-form-model-item>
        </a-form-model>
      </a-modal>

      <a-modal v-model="showInfoStatus" v-if="district.length > 0" :width="700" title="添加运费规则" @ok="handleOk">
        <a-row>
          <a-tree
            style="display: flex; flex-wrap: wrap"
            :blockNode="true"
            :checkable="true"
            @check="(e) => onSelectCheck(e)"
            multiple
          >
            <a-tree-node
              :style="{ width: '33%', display: 'flex', flexWrap: 'wrap' }"
              v-for="province of district"
              :key="JSON.stringify({ id: province.id, name: province.name, type: 'province' })"
              :title="province.name"
            >
              <a-tree-node
                v-for="city of province.cityAll"
                :isLeaf="true"
                :key="JSON.stringify({ id: city.id, name: city.name, type: 'city' })"
                :title="city.name"
              >
              </a-tree-node>
            </a-tree-node>
          </a-tree>
        </a-row>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import {
  orderRulesBuyerLocationList,
  orderRulesBuyerLocationSave,
  orderRulesBuyerLocationStatus,
  orderRulesBuyerLocationInfo,
  districtInfo,
} from '@/api/setting/salesRules'

export default {
  data() {
    return {
      queryParam: {
        is_enable: '-1',
      },

      labelCol: { span: 4 },
      wrapperCol: { span: 20 },

      form: {
        name: '',
        is_enable: '1',
      },
      province_list: [],

      rules: {
        name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
        is_enable: [{ required: true, message: '是否启用', trigger: 'change' }],
      },

      list: [],
      selectedRowKeys: [],

      totalCount: 0,
      pageSize: 10,
      pageNo: 1,
      loading: false,
      visible: false,

      columns: [
        {
          title: '规则名称',
          dataIndex: 'name',
          key: 'name',
          ellipsis: true,
        },
        {
          title: '是否开启',
          scopedSlots: { customRender: 'switch' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          width: 150,
        },
      ],

      statusList: [
        { id: '-1', name: '全部' },
        { id: '1', name: '已开启' },
        { id: '0', name: '已关闭' },
      ],

      showInfoStatus: false, // 是否展示地区
      district: [],
      selectData: [], // 选中的数据
    }
  },

  computed: {
    getTitle() {
      return this.form.id ? '编辑规则' : '新增规则'
    },
  },

  watch: {
    visible(e) {
      if (!e) {
        this.resetForm()
      }
    },
  },

  methods: {
    onSelectCheck(value) {
      var arr = []
      value.forEach((element) => {
        if (JSON.parse(element).type === 'city') {
          arr.push(JSON.parse(element))
        }
      })
      this.selectData = arr
    },

    // 分页器页数修改回调
    paginationSizeChange(current, size) {
      this.pageSize = size
      this.getList(current)
    },

    getList(pageNo = 1) {
      this.loading = true
      let { queryParam, pageSize } = this
      orderRulesBuyerLocationList({
        ...queryParam,
        pageNo,
        pageSize,
      })
        .then((res) => {
          this.loading = false

          if (!res.code) {
            this.pageNo = pageNo
            this.list = res.data.list
            return
          }

          this.$message.error(res.msg)
        })
        .catch(() => {
          this.loading = false
        })
    },

    // 批量操作
    handleAll(type, status) {
      let selectedRowKeys = this.selectedRowKeys

      if (!selectedRowKeys.length) {
        return this.$message.error('请至少选择一条选项！')
      }

      selectedRowKeys = selectedRowKeys.join(',')
      switch (type) {
        case 'remove':
          this.Status(selectedRowKeys, status)
          break
        case 'change':
          this.Status(selectedRowKeys, status)
          break
      }
    },

    async handleItem(type, scope) {
      switch (type) {
        case 'edit':
          const hide = this.$message.loading('核销中...', 0),
            res = await orderRulesBuyerLocationInfo({
              id: scope.id,
            })
          hide()
          if (!res.code) {
            let { detail, name, is_enable, id } = res.data.model
            this.form = {
              name,
              is_enable,
              id,
            }
            this.province_list = JSON.parse(detail)
            this.visible = true
            return
          }
          this.$message.error(res.msg)
          break

        case 'remove':
          this.Status(scope.id, '2')
          break

        case 'change':
          this.Status(scope.id, scope.is_enable === '1' ? '0' : '1')
          break
      }
    },

    Status(ids, status) {
      // 0.禁用 1.启用 2.删除
      orderRulesBuyerLocationStatus({
        ids,
        status,
      }).then((res) => {
        if (!res.code) {
          this.$message.success('操作成功')
          this.selectedRowKeys = []
          this.getList()
          return
        }

        this.$message.error(res.msg)
      })
    },

    // 选中多行
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { form: rule, province_list } = this

          this.loading = true
          orderRulesBuyerLocationSave({
            rule,
            province_list,
          }).then((res) => {
            if (!res.code) {
              this.$message.success('操作成功！')
              this.visible = false
              this.loading = false

              this.form = {
                name: '',
                is_enable: '1',
              }
              this.province_list = []

              this.getList()
              return
            }

            this.$message.error(res.msg)
          })
        } else {
          return false
        }
      })
    },

    resetForm() {
      this.$refs.ruleForm.resetFields()
    },

    handleOk() {
      this.showInfoStatus = false
      var data = {
        province_list: this.selectData,
      }
      this.province_list.push(data)
    },
  },

  async created() {
    this.getList()
    const res = await districtInfo()

    if (!res.code) {
      this.district = res.data.district || []
    }
  },
}
</script>

<style lang="less" scoped>
.flex {
  display: flex;

  .slot {
    border: 1px solid #d9d9d9;
    border-left: 0;
    border-radius: 0 4px 4px 0;
    height: 32px;
    width: 32px;
    background: rgba(247, 247, 247, 1);
    text-align: center;
  }
}
</style>
